package com.simosnipe.roomreserved;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Instances;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

	public List<String[]> event_list; // event_list[0] = DTSTART, event_list[1] = DTEND, event_list[2] = TITLE, event_list[3] = ORGANIZER, event_list[4] = TRUE ( if current)
	public String room_status = "FREE"; 
	public long next24h_miliseconds = 1000*60*60*24;
	public long warning_time_miliseconds = 1000*60*15;
	public int base_font_size;
	
	public String room_name;

    public SharedPreferences.OnSharedPreferenceChangeListener settings_change_listener = new SharedPreferences.OnSharedPreferenceChangeListener() 
    {
  	  public void onSharedPreferenceChanged(SharedPreferences preferences, String key) 
  	  {
  		  base_font_size = Integer.parseInt(preferences.getString("text_size", "10"));
  		  room_name = preferences.getString("room_name", "");
  		  set_room_name();
  		  refresh_events();
  		  Toast.makeText(MainActivity.this, "Settings changed.", Toast.LENGTH_LONG).show();
  		  Log.i(TAG, "Settings changed. base_font_size = " + base_font_size + " , room_name = " + room_name);
  	  }
  	};
  	
	private final Handler handler = new Handler();
	private static final String TAG = "RoomReserved";
	
	private int green_color = 0xFF52FF52;
	private int red_collor = 0xFFFF5252;
	private int orange_collor = 0xFFFFCD00;
	private SharedPreferences preferences;

	
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        base_font_size = Integer.parseInt(preferences.getString("text_size", "10"));
        room_name = preferences.getString("room_name", "");
        preferences.registerOnSharedPreferenceChangeListener(settings_change_listener);
        setContentView(R.layout.activity_main);
        set_room_name();
        refresh_events();
        doTheAutoRefresh();
    }

    private void doTheAutoRefresh() {
        handler.postDelayed(new Runnable() {
                 public void run() {
                	 refresh_events();
                     doTheAutoRefresh();                
                 }
             }, 5000);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_refresh:
            	refresh_events();
                return true;
            case R.id.menu_settings:
            	Intent settings_activity = new Intent(MainActivity.this, SettingsActivity.class);
                startActivity(settings_activity);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

  
    
    private void set_room_name()
    {
    	TextView room_name_tv = (TextView) findViewById(R.id.text_room_name);
    	room_name_tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, base_font_size + 5);
    	room_name_tv.setText(room_name);
//    	Cursor cursor = getContentResolver().query(Calendars.CONTENT_URI, null, null, null, null);
//    	String callendar_name = "";
//    	String callendar_display_name = "";
//    	String callendar_owner_account = "";
//    	
//    	while (cursor.moveToNext())
//    	{
//    		callendar_name = cursor.getString(cursor.getColumnIndex(Calendars.NAME));
//    		callendar_display_name = cursor.getString(cursor.getColumnIndex(Calendars.CALENDAR_DISPLAY_NAME));
//    		callendar_owner_account = cursor.getString(cursor.getColumnIndex(Calendars.OWNER_ACCOUNT));
//    	}
//    	TextView room_name_tv = (TextView) findViewById(R.id.text_room_name);
//    	if (callendar_name != null && !callendar_name.isEmpty())
//    	{
//    		room_name_tv.setText(callendar_name);
//    	}
//    	else if (callendar_display_name != null && !callendar_display_name.isEmpty())
//    	{
//    		room_name_tv.setText(callendar_display_name);
//    	}
//    	else if (callendar_owner_account != null && !callendar_owner_account.isEmpty())
//    	{
//    		room_name_tv.setText(callendar_owner_account);
//    	}
    	    	
    }
    
    public void refresh_events()
    {
    	LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
    	ll.removeAllViews();
    	event_list = new ArrayList<String[]>();
    	get_event_list(next24h_miliseconds);
       	Log.i(TAG, "Events refreshed room_status = " + room_status);
    	sort_event_list();
        show_events();
    }
    
    public void get_event_list(long future_limit) { //future_limit time in epoch miliseconds
    	room_status = "FREE";
    	long now = System.currentTimeMillis();
    	long future_scope = now + future_limit;
    	Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon();
    	ContentUris.appendId(eventsUriBuilder, now);
    	ContentUris.appendId(eventsUriBuilder, future_scope);
    	Uri eventsUri = eventsUriBuilder.build();
    	Cursor cursor = getContentResolver().query(eventsUri, null, null, null, Instances.DTSTART + " ASC");
    	while (cursor.moveToNext())
    	{
    		String event_id = cursor.getString(cursor.getColumnIndex(Instances.EVENT_ID));
    		String event_start_string = cursor.getString(cursor.getColumnIndex(Instances.BEGIN));
    		String event_end_string = cursor.getString(cursor.getColumnIndex(Instances.END));
    		String event_title = get_event_title(event_id);
    		String event_organizer = get_event_organizer(event_id);
       		if (event_start_string != null && !event_start_string.isEmpty() && event_end_string != null && !event_end_string.isEmpty())
    		{
	    		long event_start_long = Long.valueOf(event_start_string).longValue();
	    		long event_end_long = Long.valueOf(event_end_string).longValue();
	    		if (event_end_long > now && event_start_long < future_scope) 
	    		{
	    			String status = "FREE";
	        		if (event_start_long <= now && event_end_long > now)
	        		{
	        			status = "NOW";
	        		}
	        		else if (event_start_long > now && event_start_long < (now + warning_time_miliseconds))
	        		{
	        			status = "NEAR";
	        		}
	        		else
	        		{
	        			status = "FUTURE";
	        		}
	        		event_list.add(new String[] { event_start_string, event_end_string, event_title, event_organizer, status });
	        		
	        		if (status == "NOW")
	        		{
	        			room_status = "NOW";
	        		}
	        		else if (status == "NEAR")
	        		{
		        		if (room_status != "NOW")
		        		{
		        			room_status = "NEAR";
		        		}
	        		}
	    		}
    		}
    	}
    }

	
    
    public String get_event_title(String event_id)
    {
    	long event_id_long = Long.valueOf(event_id).longValue();
    	Uri event_Uri = ContentUris.withAppendedId(Events.CONTENT_URI, event_id_long);
    	Cursor cursor = getContentResolver().query(event_Uri, null, null, null, null);
    	String event_title = "";
    	while (cursor.moveToNext())
    	{
    		event_title = cursor.getString(cursor.getColumnIndex(Events.TITLE));
    	}
    	return event_title;
    }
    
    public String get_event_organizer(String event_id)
    {
    	long event_id_long = Long.valueOf(event_id).longValue();
    	Uri event_Uri = ContentUris.withAppendedId(Events.CONTENT_URI, event_id_long);
    	Cursor cursor = getContentResolver().query(event_Uri, null, null, null, null);
    	String event_organizer = "";
    	while (cursor.moveToNext())
    	{
    		event_organizer = cursor.getString(cursor.getColumnIndex(Events.ORGANIZER));
    	}
    	return event_organizer;
    }
    
    public void sort_event_list() 
    {
    	Collections.sort(event_list ,new Comparator<String[]>() 
    			{
            		public int compare(String[] strings, String[] otherStrings) {
            		return strings[0].compareTo(otherStrings[0]);
            	}
        });
    	Log.i(TAG, "Events sorted");
    }
    	
    public void show_events() 
    {
    	LinearLayout ll = (LinearLayout) findViewById(R.id.linearLayout1);
//    	LinearLayout ll_top = (LinearLayout) findViewById(R.id.linearLayoutTop);
    	LinearLayout ll_root = (LinearLayout) findViewById(R.id.linearLayoutRoot);
    	if (room_status == "NOW")
    	{
    		ll_root.setBackgroundColor(red_collor);
    	}
    	else if (room_status == "NEAR")
    	{
    		ll_root.setBackgroundColor(orange_collor);
    	}
    	else 
    	{
    		ll_root.setBackgroundColor(green_color);
    	}    		
    	String event_title ="";
    	String event_organizer = "";
    	String event_start_hour;
    	String event_end_hour;
    	SimpleDateFormat hours_format = new SimpleDateFormat("HH:mm");
    	if (event_list.size() > 0)
    	{
	    	for(String[] event_tab: event_list)
	    	{
	    		event_title = event_tab[2];
	    		if (event_title.length() > 40)
	    			event_title = event_title.substring(0, 40) + "...";
	    		event_organizer = event_tab[3];
	    		event_start_hour = hours_format.format(new Date(Long.parseLong(event_tab[0])));
	    		event_end_hour = hours_format.format(new Date(Long.parseLong(event_tab[1])));
	        	String event_text = event_start_hour + " - " + event_end_hour + "\n" +  event_title + "\n" + event_organizer ;
	        	View line = new View(this);
	        	line.setLayoutParams(new LayoutParams(-1 , 2)); //-1 = match_parrent
	        	line.setBackgroundColor(0xFF000000);
	        	TextView tv = new TextView(this);
	    	    if (event_tab[4] == "NOW")
	    	    {
	    	    	tv.setTypeface(null, Typeface.BOLD);
	    	    }
	    	    tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, base_font_size);
	    	    tv.setGravity(Gravity.CENTER_HORIZONTAL);
	        	tv.setText(event_text);
	        	ll.addView(line);
	        	ll.addView(tv);
	    	}
	    	View line = new View(this);
	    	line.setLayoutParams(new LayoutParams(-1 , 2));
	    	line.setBackgroundColor(0xFF000000);
	    	ll.addView(line);
    	}
    	else
    	{
    		TextView tv = new TextView(this);
    		tv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    	    tv.setGravity(Gravity.CENTER);
    	    tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, base_font_size + 10);
        	tv.setText("FREE");
        	ll.addView(tv);
    	}
    }
}
